package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * * @title: UserInfoService
 *
 * @Author Philcan
 * @Date: 2021/8/8 19:20
 * @Version 1.0
 */
@Service
public class UserInfoService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private PicUploadService picUploadService;

    public boolean saveUserInfo(Map<String, String> param, String token) {
        User user = this.userService.queryUserByToken(token);
        if (null == user) {
            return false;
        }
        UserInfo userInfo = UserInfo.builder().userId(user.getId()).sex(StringUtils.equalsIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN)
                .nickName(param.get("nickname")).birthday(param.get("birthday")).city(param.get("city")).build();
        return this.userInfoMapper.insert(userInfo) == 1;
    }

    public boolean saveUserLogo(MultipartFile file, String token) {
        User user = this.userService.queryUserByToken(token);
        if (null == user) {
            return false;
        }
        try {
            boolean b = this.faceEngineService.checkIsPortrait(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        PicUploadResult upload = this.picUploadService.upload(file);
        if (StringUtils.isEmpty(upload.getName())) {
            return false;
        }
        UserInfo userInfo = UserInfo.builder().logo(upload.getName()).build();
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        return this.userInfoMapper.update(userInfo, queryWrapper) == 1;
    }
}
